<?php

namespace App\Http\Controllers\Admin\AirLine;

use App\Http\Controllers\Controller;
use App\Models\DepotBanItemModel;
use App\Models\DepotBanModel;
use App\Models\DictionaryModel;
use App\Models\FlightBanModel;
use App\Models\FlightBansModel;
use App\Models\FlightModel;
use App\Models\OrderModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;



class ActualBan extends Controller
{

    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $code = $request->input('code', '');
        $route_id = $request->input('route_id', '');
        $airline_flight_id = $request->input('airline_flight_id', '');
        $take_off_time_start = $request->input('startTime', '');
        $take_off_time_end = $request->input('endTime', '');
        $carrier = $request->input('carrier', '');


        $query = FlightBansModel::withWhereHas('flight', function ($query) use ($airline_flight_id, $route_id, $take_off_time_start, $take_off_time_end, $carrier) {
            $query->with('items');
            if($route_id || $airline_flight_id){
                $query->whereHas('items', function ($query) use ($route_id, $airline_flight_id) {
                    if($route_id){
                        $query->where('route_id', $route_id);
                    }
                    if($airline_flight_id){
                        $query->where('airline_flight_id', $airline_flight_id);
                    }
                });
            }

            if($take_off_time_start && $take_off_time_end){
                $query->whereBetween('take_off_time', [$take_off_time_start, $take_off_time_end]);
            }
            if($carrier){
                $query->where('carrier', $carrier);
            }
        });

        if($code){
            $query->where('code', $code);
        }

        $total = $query->count('id');
        $total_weight = $query->sum('weight');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {

            $flight_lines = $item->flight->items;
            $flight_no = [];
            $routes = [];
            if($flight_lines){
                foreach($flight_lines as $flight_line) {
                    $flight_number = $flight_line->air_line->flight_number ?? '';
                    $date = $flight_line->date ?? '';

                    if($date){
                        $d = new \DateTime($date);
                        $date = $d->format('d.M');
                    }

                    $flight_no[] = $flight_number . '/' . $date;
                    $routes[] = $flight_line->route->code ?? '';
                }
            }

            return [
                'id' => $item->id,
                'flight_no' => implode(',', $flight_no),
                'routes' => implode(',', $routes),
                'main_sn' =>  $item->flight->main_sn ??  '',
                'take_off_time' => $item->flight->take_off_time ?? '',
                'code' => $item->code,
                'weight' => $item->weight,
                'carrier' => $item->flight->carrier ?? '',
            ];
        });

        $statistics = [
            'ban_count' => $total,
            'total_weight' => $total_weight,
        ];

        return $this->success(['list' => $list, 'total' => $total, 'statistics' => $statistics]);
    }


    public function order_list(Request $request)
    {
        $id = $request->input('id');

        $find = DepotBanItemModel::with(['order' => function ($query) {
            $query->with(['customer', 'des_country', 'take_order']);
        }])->where('depot_ban_id', $id)->get();

        if(!$find){
            return $this->error('数据不存在');
        }

        $list = $find->map(function($item) {
            $packages = $item->order->packages ?? '';
            $packages = DictionaryModel::whereIn('id', explode(',', $packages))
                ->pluck('name')
                ->implode('+');

            return [
                'customer_name' => $item->order->customer->name ?? '',
                'order_sn' => $item->order->sn,
                'take_order_sn' => $item->order->take_order->sn ?? '',
                'big_pkgs' => $item->order->big_pkgs,
                'pre_out_date' => $item->order->pre_out_date,
                'des_country' => $item->airport->country_name ?? '',
                'goods_attr' => OrderModel::GOODS_ATTR_MAPS[$item->order->goods_attr] ?? '',
                'pre_volume' => $item->order->pre_volume,
                'pre_weight' => $item->order->pre_weight,
                'storage_weight' => $item->order->storage_weight,
                'packages' => $packages,
            ];
        });

        return $this->success(['list' => $list]);
    }

    public function pivot(Request $request){
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $ban_id = $request->input('ban_id', '');
        $route_id = $request->input('route_id', '');
        $flight_number = $request->input('flight_number', '');
        $take_off_time_start = $request->input('startTime', '');
        $take_off_time_end = $request->input('endTime', '');
        $carrier = $request->input('carrier', '');


        $query = FlightBanModel::with('ban')->withWhereHas('flight', function ($query) use ($flight_number, $route_id, $carrier, $take_off_time_start, $take_off_time_end) {
            $query->with('items');
            if($flight_number){
                $query->where('flight_number', $flight_number);
            }
            if($route_id){
                $query->whereHas('items', function ($query) use ($route_id) {
                    $query->where('route_id', $route_id);
                });
            }

            if($take_off_time_start && $take_off_time_end){
                $query->whereBetween('take_off_time', [$take_off_time_start, $take_off_time_end]);
            }
            if($carrier){
                $query->where('carrier', $carrier);
            }
        });

        if($ban_id){
            $query->where('ban_id', $ban_id);
        }

        $total = $query->count('id');

        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {

            $flight_lines = $item->flight->items;
            $flight_no = [];
            $routes = [];
            if($flight_lines){
                foreach($flight_lines as $flight_line) {
                    $flight_number = $flight_line->air_line->flight_number ?? '';
                    $date = $flight_line->date ?? '';

                    if($date){
                        $d = new \DateTime($date);
                        $date = $d->format('d.M');
                    }

                    $flight_no[] = $flight_number . '/' . $date;
                    $routes[] = $flight_line->route->code ?? '';
                }
            }

            return [
                'id' => $item->id,
                'flight_no' => implode(',', $flight_no),
                'routes' => implode(',', $routes),
                'main_sn' =>  $item->flight->main_sn ??  '',
                'take_off_time' => $item->flight->take_off_time ?? '',
                'ban_name' => $item->ban->name ?? '',
                'nums' => $item->nums,
                'pivot' => $item->ban->pivot ?? '',
                'total_pivot' => $item->ban->pivot ? $item->ban->pivot * $item->nums : '',
                'ban_di' => $item->ban->ban_di ?? '',
                'carrier' => $item->flight->carrier ?? '',
            ];
        });;


        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function flight(Request $request){
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $startTime = $request->input('startTime', '');
        $endTime = $request->input('endTime', '');
        $agent_id = $request->input('agent_id', '');
        $start_port_code = $request->input('start_port_code', '');
        $arrive_port_code = $request->input('arrive_port_code', '');
        $airline_company_id = $request->input('airline_company_id', '');
        $destination_id = $request->input('destination_id', '');

        $query = FlightModel::with(['items','take_orders','bans', 'orders'])->whereHas('items', function ($query) use ($agent_id, $airline_company_id){
            if($agent_id){
                $query->whereHas('air_company', function ($query) use ($agent_id){
                    $query->where('agent_id', $agent_id);
                });
            }
            if($airline_company_id){
                $query->where('airline_company_id', $airline_company_id);
            }
        });

        if($start_port_code){
            $query->where('start_port_code', $start_port_code);
        }
        if($arrive_port_code){
            $query->where('arrive_port_code', $arrive_port_code);
        }

        if($startTime && $endTime){
            $query->whereBetween('take_off_time', [$startTime, $endTime]);
        }


        $total = $query->count('id');
        $items = $query
            ->withCount('take_orders')
            ->withCount('orders')
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $flight_no = [];
            $routes = [];

            foreach($item->items as $flight_line) {
                $flight_number = $flight_line->air_line->flight_number ?? '';
                $date = $flight_line->date ?? '';

                if($date){
                    $d = new \DateTime($date);
                    $date = $d->format('d.M');
                }

                $flight_no[] = $flight_number . '/' . $date;
                $routes[] = $flight_line->route->code ?? '';
            }


            $ban_nums = 0;
            $ban_info = [];
            foreach($item->bans as $ban) {
                $ban_nums += $ban->nums;
                $ban_info[] = $ban->ban->name ?? '' . '*' . $ban->nums;
            }

            $total_weight = round($item->orders->sum('storage_weight') ?? 0, 2);
            $total_volume = round($item->orders->sum('storage_volume') ?? 0, 2);


            return [
                'id' => $item->id,
                'status' => $item->status,
                'flight_no' => implode(',', $flight_no),
                'routes' => implode(',', $routes),
                'main_sn' =>  $item->main_sn,
                'take_off_time' => $item->take_off_time,
                'landing_time' => $item->landing_time,
                'bans' => $item->bans,
                'ban_info' => $ban_info,
                'volume' => $item->volume,
                'weight' => $item->weight,
                'take_order_count' => $item->take_orders_count,
                'order_count' => $item->orders_count,
                'ban_count' => $ban_nums,
                'total_weight' => $total_weight,
                'total_volume' => $total_volume,
                'carrier' => $item->carrier,
            ];
        });

        $list = $list->toArray();
        $statistics = [
            'ban_count' => array_sum(array_column($list, 'ban_count')),
            'order_count' => array_sum(array_column($list, 'order_count')),
            'total_weight' => round(array_sum(array_column($list, 'total_weight')), 2),
            'total_volume' => round(array_sum(array_column($list, 'total_volume')), 2),
            'take_order_count' => array_sum(array_column($list, 'take_order_count')),
        ];

        return $this->success(['list' => $list, 'total' => $total, 'statistics' => $statistics]);
    }
}